define(['jquery', 'bootstrap', 'backend', 'table', 'form','util'], function ($, undefined, Backend, Table, Form,Util) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'xilujob.job_manage/index' + location.search,
                    add_url: 'xilujob.job_manage/add',
                    edit_url: 'xilujob.job_manage/edit',
                    del_url: 'xilujob.job_manage/del',
                    multi_url: 'xilujob.job_manage/multi',
                    apply_url: 'xilujob.job_apply/index',
                    interview_url: 'xilujob.job_interview/index',
                    table: 'xilujob_job',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'updatetime',
                search: false, //是否启用快速搜索
                commonSearch: true, //是否启用通用搜索
                searchFormVisible: true, //是否始终显示搜索表单
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate:false,visible:false},
                        {field: 'job_name', title: __('职位名称'), operate:'LIKE',visible:false},
                        {field: 'education_level_id', title: __('学历'),searchList: Config.education_level,visible: false},
                        {field: 'work_experience_id', title: __('工作经验'),searchList: Config.work_experience,visible: false},

                        {field: 'job', title: __('职位信息'),align:'left', formatter: function(value,row){
                            var html = '';
                            html += row.job_name+'<br />';
                            html += row.city.name+'－'+row.district.name +' | '
                                + row.work_experience.name +' | '
                                + row.education_level.name + ' | '
                                + row.salary_text;
                             return html;
                            },operate:false},
                        {field: 'apply_count', title: __('应聘简历'), operate:false},
                        {field: 'view_count', title: __('浏览量'), operate:false},
                        {field: 'status', title: __('状态'),searchList: {2:'待审核',1:'已上架',0:'已下架',3:'未通过'},formatter: Table.api.formatter.status},
                        // {field: 'job_info.failed_reason', title: __('未通过原因'),operate:false},
                        {field: 'createtime', title: __('添加时间'),operate:'RANGE',addclass:'datetimerange',formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'),buttons: [
                                {
                                    name: 'apply',
                                    title: '应聘简历',
                                    text: '应聘简历',
                                    extend: 'data-toggle="tooltip"',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: '',
                                    url: function (row) {
                                        return $.fn.bootstrapTable.defaults.extend.apply_url+'?job_id='+row.id
                                    }
                                },
                                {
                                    name: 'refresh',
                                    title: '刷新',
                                    text: '刷新',
                                    extend: 'data-toggle="tooltip"',
                                    classname: 'btn btn-xs btn-success btn-click',
                                    icon: '',
                                    click: function (option,row,button) {
                                        Layer.confirm('确认刷新？', function(index) {
                                            Fast.api.ajax({
                                                url: 'xilujob.job_manage/refresh_job?id='+row.id, data: {}
                                            }, function(data,ret) {
                                                $(".btn-refresh").trigger("click");
                                            },function (data,ret) {
                                                Toastr.error(ret.msg);
                                            });
                                            Layer.close(index);
                                        });
                                    },
                                    visible: function (row) {
                                        return row.status===1;
                                    }
                                },
                                {
                                    name: 'promote',
                                    title: '推广',
                                    text: '推广',
                                    extend: 'data-toggle="tooltip"',
                                    classname: 'btn btn-xs btn-success btn-click',
                                    icon: '',
                                    click: function (option,row,button) {
                                        Layer.alert('需要对职位推广，请联系客服。');
                                    },
                                },
                                {
                                    name: 'edit',
                                    title: '编辑',
                                    text: '编辑',
                                    extend: 'data-toggle="tooltip"',
                                    classname: 'btn btn-xs btn-success btn-click',
                                    icon: '',
                                    click: function (option,row,button) {
                                       if(row.status != 1){
                                            Fast.api.open("xilujob.job_manage/edit?ids="+row.id,'编辑',{area:["80%","95%"]});
                                       }else{
                                           Layer.alert('下架后再修改编辑');
                                       }
                                    },
                                    visible: function (row) {
                                        return true;
                                    }
                                },
                                {
                                    name: 'pause',
                                    title: '下架',
                                    text: '下架',
                                    extend: 'data-toggle="tooltip"',
                                    classname: 'btn btn-xs btn-success btn-click',
                                    icon: '',
                                    click: function (option,row,button) {
                                        Layer.confirm('确认下架？', function(index) {
                                            Fast.api.ajax({
                                                url: 'xilujob.job_manage/switch_off', data: {id:row.id}
                                            }, function(data,ret) {
                                                $(".btn-refresh").trigger("click");
                                            });
                                            Layer.close(index);
                                        });
                                    },
                                    visible: function (row) {
                                        return row.status == 1;
                                    }
                                },
                                {
                                    name: 'piblish',
                                    title: '上架',
                                    text: '上架',
                                    extend: 'data-toggle="tooltip"',
                                    classname: 'btn btn-xs btn-success btn-click',
                                    icon: '',
                                    click: function (option,row,button) {
                                        Layer.confirm('确认上架？', function(index) {
                                            Fast.api.ajax({
                                                url: 'xilujob.job_manage/switch_on', data: {id:row.id}
                                            }, function(data,ret) {
                                                $(".btn-refresh").trigger("click");
                                            });
                                            Layer.close(index);
                                        });
                                    },
                                    visible: function (row) {
                                        return row.status == 0;
                                    }
                                },
                                {
                                    name: 'del',
                                    title: '删除',
                                    text: '删除',
                                    extend: 'data-toggle="tooltip"',
                                    classname: 'btn btn-xs btn-danger btn-click',
                                    icon: '',
                                    click: function (option,row,button) {
                                        Layer.confirm('确认删除？', function(index) {
                                            Fast.api.ajax({
                                                url: 'xilujob.job_manage/del', data: {id:row.id}
                                            }, function(data,ret) {
                                                $(".btn-refresh").trigger("click");
                                            });
                                            Layer.close(index);
                                        });
                                    },
                                    visible: function (row) {
                                        return true;
                                    }
                                },
                            ], table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            table.on('load-success.bs.table',function(data){
                $('.btn-add,.btn-apply').data("area", ["80%","95%"]);
            });

            $('#add').on('click', function (e) {
                var msg = $(this).data('msg');
                if(msg) {
                    e.preventDefault();
                    Layer.confirm(msg, {
                        btn: ['联系升级','稍后再说']
                    },function (index) {
                        window.open("http://wpa.qq.com/msgrd?v=3&uin={{qq}}&site=qq&menu=yes".bind({qq:Config.site.pc_qq_service}));
                        Layer.close(index);
                    });
                }
            });
        },
        add: function () {
            this.edit();
        },
        edit: function () {
            let areas = Config.areas;
            require(['../addons/xilujob/js/scroll-select','../addons/xilujob/js/jquery.serialize-object.min'], function () {
                var categoryPicker = new ScrollSelect({
                    source_url:Fast.api.fixurl('xilujob.user/job_categories'),
                    name_key: 'category_name', children_key: 'childlist',
                    data_parser: function (rawData) {
                        if(rawData.code===1) {
                            return rawData.data;
                        }
                        return [];
                    },on_select:function (selectedDatas, level, targetElement) {
                        if(level!=this.maxLevel) {
                            return;
                        }
                        $(targetElement).siblings('input:hidden').val(selectedDatas[level-1].id);
                        $(targetElement).val(selectedDatas[level-1].category_name);
                        categoryPicker.hide();
                    }
                });
                $('#select-category').on('click', function () {
                    categoryPicker.show(this);
                });

                (function(){
                    //发布区域选择
                    var picker = new ScrollSelect({
                        data:areas, max_level:3,
                        on_select:function(rows, level) {
                            console.log(rows)
                            if(level==3) {
                                $('input[name="job[province_id]"]').val(rows[0].id);
                                $('input[name="job[city_id]"]').val(rows[1].id);
                                $('input[name="job[district_id]"]').val(rows[2].id);
                                //$('input[name="job[town_id]"]').val(rows[1].id);
                                var value = [];
                                rows.forEach(function (item) {
                                    value.push(item.name);
                                });
                                $('#pick-area').val(value.join(' - '));
                                this.hide();
                            }
                        }
                    });
                    $('#pick-area').on('click', function () {
                        picker.show(this);
                    });
                })();
                //工作区域
                var areaPicker = new ScrollSelect({
                    data:areas, max_level:3,
                    on_select:function(rows, level, targetElement) {
                        if(level<3)
                            return;
                        $(targetElement).siblings('input[name="job[locations][][province_id]"]').val(rows[0].id);
                        $(targetElement).siblings('input[name="job[locations][][city_id]"]').val(rows[1].id);
                        $(targetElement).siblings('input[name="job[locations][][district_id]"]').val(rows[2].id);
                        var value = [];
                        rows.forEach(function(item){
                            value.push(item.name);
                        });
                        $(targetElement).val(value.join(','));
                        this.hide();
                    }
                });
                $('#job-form').on('click', '.select-area', function () {
                    areaPicker.show(this);
                })
            });
            Util.bindSelect('.ul-selector');
            $('.type-radio').on('click', function (event) {
                $(this).addClass('active').siblings('.type-radio').removeClass('active');
                $(this).find('input:radio').prop('checked',true);
            });
            $(document).on('click', '.type-checkbox', function (event) {
                if($(this).hasClass('active')) {
                    $(this).removeClass('active');
                    $(this).find('input:checkbox').prop('checked', false);
                }else {
                    $(this).addClass('active');
                    $(this).find('input:checkbox').prop('checked', true);
                }
            });
            $('#add-benefit').on('click', function () {
                Layer.prompt({title:'请输入',maxlength:10},function(value,index,elem) {
                    value = value.trim();
                    if(value==='') {
                        Toastr.error('请输入名称');
                        return;
                    }
                    var $benefits = $('#benefits #items').children('.type-checkbox');
                    for(var i=0;i<$benefits.length;i++) {
                        if($benefits.eq(i).text()===value) {
                            //在列表中，如果未选中则选中
                            if(!$benefits.eq(i).hasClass('active')) {
                                $benefits.eq(i).click();
                            }
                            Layer.close(index);
                            return;
                        }
                    }
                    //
                    Fast.api.ajax({url:'xilujob.job_manage/get_benefit',data:{name:value}}, function (data, ret) {
                        var benefit = data.benefit;
                        $benefits.eq($benefits.length-1).after('<div style="cursor: pointer;" class="item type-checkbox active"><input type="checkbox" name="job[benefit_ids][]" value="'+benefit.id+'" style="display: none;" checked /> '+benefit.name+'</div>');
                    });
                    Layer.close(index);
                });
            });
            //选择薪资结算类型
            $('#c-salary_type').on('change',function() {
                var value = $(this).val();
                if(value==='0') {
                    $('#salary-inputs').hide().find('input').val('');
                }else {
                    $('#salary-inputs').show();
                }
            });
            //添加工作地址
            $('#job-form').on('click', '.btn-add-location',function () {
                var template = $('#location-template').text();
                var $location = $(template);
                $('#locations').append($location);
            }).on('click', '.btn-remove-location', function() {
                if($('.location').length===1) {
                    Toastr.error('至少添加一个工作地点');
                    return;
                }
                var $location = $(this).closest('.location');
                Layer.confirm('确认删除工作地点？',function (index) {
                    $location.remove();
                    Layer.close(index);
                    $('.location').eq(0).find('.t_title').text('工作地点：').end().siblings('.location')
                        .find('.t_title'.text(''));
                });
            }).data("validator-options", {
                rules: {
                    'salary_max': function(element) {
                        var salaryMin = parseInt($('input[name="row[salary_min]"]').val());
                        var salaryMax = parseInt($('input[name="row[salary_max]"]').val());
                        if(salaryMax!==0&&salaryMax<salaryMin) {
                            return '最高薪资必须大于最低薪资';
                        }
                    },
                    'salaryInput': function() {
                        return $('#c-salary_type').val()!=='0';
                    }
                }
            });

            var action;
            Form.api.bindevent('#job-form', function(data, ret) {
                setTimeout(function () {
                    location.href = ret.url;
                }, 1000);

            }, function(data, ret) {

            }, function(success, error) {
                if(action==='submit') {
                    try {
                        var data = this.serializeJSON();
                        Fast.api.ajax({url: '', data: data, contentType: 'application/json'}, success, error);
                    }catch (e) {
                        console.error(e);
                    }
                }else if(action==='preview') {
                    var data = $('#job-form').serializeJSON();
                    window.open(Fast.api.fixurl('xilujob.job_manage/preview')+'?data='+(data));
                    // location.href = Fast.api.fixurl('job_manage/preview')+'?data='+(data);
                }
                return false;
            });
            $('#btn-preview').on('click', function () {
                action = 'preview';
                $('#job-form').submit();

            });
            $('#btn-save').on('click', function () {
                action = 'submit';
                $('#job-form').submit();
            });

            // 免责声明
            $('.xieyi').click(function () {
                $('.zz').show()
                $('.mask_xieyi').show()
            })
            $('.zz,.mask_xieyi_btn').click(function () {
                $('.zz').hide()
                $('.mask_xieyi').hide()
            })

            Controller.api.bindevent();
        },
        working_place: function () {
            Controller.api.bindevent();
        },
        preview: function () {
            $('#submit').on('click',function (data, ret) {
                var url = jobData.id ? 'xilujob.job_manage/edit/id/'+jobData.id : 'xilujob.job_manage/add';
                Fast.api.ajax({
                    url: url,
                    data: {job: jobData}
                },function (data, ret) {
                    setTimeout(function () {
                        location.href = ret.url;
                    }, 1000);
                })
            });
        },
        api: {
            bindevent: function () {
                // Form.api.bindevent($("form[role=form]"));
                $('form[role=form]').data("validator-options", {
                    rules: {
                        'salary_max': function(element) {
                            var salaryMin = parseInt($('input[name="row[salary_min]"]').val());
                            var salaryMax = parseInt($('input[name="row[salary_max]"]').val());
                            if(salaryMax!==0&&salaryMax<salaryMin) {
                                return '最高薪资必须大于最低薪资';
                            }
                        },
                        'salaryInput': function() {
                            return $('#c-salary_type').val()!=='0';
                        }
                    }
                });

                $('#c-salary_type').on('change',function() {
                    var value = $(this).val();
                    if(value==='0') {
                        $('#salary-inputs').addClass('hide').find('input').val('');
                    }else {
                        $('#salary-inputs').removeClass('hide');
                    }
                });

                $('#c-city_id').on('change', function () {
                    var cityId = $(this).val();
                    if(!cityId)
                        return;
                    Fast.api.ajax({url:'xilujob/job/area/pid/'+cityId}, function (data, ret) {
                        var districts = data, $select = $('#c-district_id'), value = $select.data('value');
                        $select.empty().val('');
                        districts.forEach(function(item) {
                            $select.append('<option '+(item.value==value?'selected':'')+' value="'+item.value+'">'+item.name+'</option>');
                        });
                        $select.selectpicker('refresh');
                        $('#c-town_id').empty().val('').selectpicker('refresh');
                        if($('#c-district_id').val())
                            $('#c-district_id').trigger('change');
                        return false;
                    });
                });
                setTimeout(function(){
                    if($('#c-city_id').val())
                        $('#c-city_id').trigger('change');
                },1000);
                $('#c-district_id').on('change', function () {
                    var districtId = $(this).val();
                    if(!districtId)
                        return;
                    Fast.api.ajax({url:'xilujob/job/area/pid/'+districtId}, function (data, ret) {
                        var towns = data, $select = $('#c-town_id'), value = $select.data('value');
                        $select.empty().val('');
                        towns.forEach(function(item) {
                            $select.append('<option '+(item.value==value?'selected':'')+' value="'+item.value+'">'+item.name+'</option>');
                        });
                        $select.selectpicker('refresh');
                        return false;
                    });
                });

                $('#add-location').on('click', function () {
                    Fast.api.open(Fast.api.fixurl("xilujob/job_manage/working_place"),'添加地址',{callback:function(value){
                            console.log(value,123);
                            getAddress();
                        }
                    });
                });
                //地图
                $("[data-toggle='addresspicker']").data("callback", function(res){
                    //其中res则是包含了address/lat/lng等信息的JSON对象
                    $('[name="row[address_name]"]').val(res.address);
                    $('[name="row[address]"]').val(res.address);
                    $('[name="row[lat]"]').val(res.lat);
                    $('[name="row[lng]"]').val(res.lng);
                });
                function getAddress(){
                    Fast.api.ajax({url:'xilujob/job_manage/select_company_address'}, function (data, ret) {
                        var $select = $('#locations');
                        $('#locations .addr-box').eq(0).siblings().remove();
                        data.forEach(function(item,index) {
                            $select.find('.t_selectw').append('<label class="addr-box" for="addr'+index+'"><input' +
                                ' type="radio"' +
                                ' name="job[company_address_id]" id="addr'+index+'" value="'+item.id+'"><div class="addr"><p>'+item.address_name+'</p><p>'+item.address+'</p></div><button type="button" class="btn btn-danger del-location" data-id="'+item.id+'">删除</button></label>');
                        });
                        return false;
                    });
                }
                $('#locations').on('click','.del-location', function() {
                    if($('.location').length===1) {
                        Toastr.error('至少添加一个工作地点');
                        return;
                    }
                    let id = $(this).data('id');
                    var $location = $(this).closest('.addr-box');
                    Layer.confirm('确认删除工作地点？',function (index) {
                        Fast.api.ajax({url:'xilujob/job_manage/del_address',data:{id: id}}, function (data, ret) {
                            $location.remove();
                            Layer.close(index);
                            return false;
                        },function (data,ret) {
                            Layer.close(index);
                        });
                    });
                });
                require(['../addons/xilujob/js/jquery.serialize-object.min'],function () {
                    Form.api.bindevent($("form[role=form]"), function(data, ret) {
                        parent.$(".btn-refresh").trigger("click");
                        var index = parent.Layer.getFrameIndex(window.name);
                        parent.Layer.close(index);
                        Fast.api.close({});
                    }, function(data, ret) {

                    }, function(success, error) {
                        try {
                            var data = this.serializeJSON();
                            Fast.api.ajax({url: '', data: data, contentType: 'application/json'}, success, error);
                        }catch (e) {
                            console.error(e);
                        }
                        return false;
                    });
                })

            }
        }
    };
    return Controller;
});